<?php
// +----------------------------------------------------------------------
// | B5Yii2CMF V3.0 [快捷通用基础管理开发平台]
// +----------------------------------------------------------------------
// | Author: 冰舞 <357145480@qq.com>
// +----------------------------------------------------------------------
declare (strict_types=1);

namespace common\helpers;

use common\helpers\IpLocation\IpLocation;

class Location
{

    //获取两点地理距离
    public static function getDistance($lat1, $lng1, $lat2, $lng2): int
    {
        $earthRadius = 6378137;
        $lat1 = ($lat1 * M_PI) / 180;
        $lng1 = ($lng1 * M_PI) / 180;
        $lat2 = ($lat2 * M_PI) / 180;
        $lng2 = ($lng2 * M_PI) / 180;

        $calcLng = $lng2 - $lng1;
        $calcLat = $lat2 - $lat1;
        $s = pow(sin($calcLat / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($calcLng / 2), 2);
        $s = 2 * asin(sqrt($s)) * $earthRadius;
        return intval(round($s));
    }

    /**
     * 拼接距离sql
     * @param $latitude
     * @param $longitude
     * @param string $latitudeField
     * @param string $longitudeField
     * @param string $aliasField
     * @return string
     */
    public static function distanceSql($latitude,$longitude, string $latitudeField = 'latitude', string $longitudeField = 'longitude', string $aliasField="distance"): string
    {
       return "(round(6378138 * 2 * asin(sqrt(pow(sin((({$latitudeField} * pi()) / 180 - ({$latitude} * pi()) / 180) / 2), 2) + cos(({$latitude} * pi()) / 180) * cos(({$latitudeField} * pi()) / 180) * pow(sin((({$longitudeField} * pi()) / 180 - ({$longitude} * pi()) / 180) / 2), 2))))) AS {$aliasField}";
    }


    /**
     * 根据ip获取省份城市
     * @param $ip
     * @return string
     */
    public static function getAddressByIp($ip): string
    {
        if (!$ip) return '';
        $ip = trim(explode(',', $ip)[0]);
        if (!$ip) return '';
        $ipLocation = new IpLocation();
        $location = $ipLocation->getlocation($ip);
        $country = '';
        if ($location && isset($location['country']) && $location['country']) {
            $country = trim(iconv('GBK', 'UTF-8', $location['country']));
        }
        return $country;
    }
}
